from fastapi import APIRouter, HTTPException, Query
from fastapi.responses import JSONResponse
from typing import Optional
from pydantic import BaseModel
import traceback
from loguru import logger

from app.services.asr_service import ASRService
from app.services.video_upload_service import VideoUploadService

router = APIRouter(prefix="/api/v1", tags=["语音识别"])

# 请求模型
class TranscriptionRequest(BaseModel):
    language: Optional[str] = None

# 响应模型
class TranscriptionResponse(BaseModel):
    success: bool
    message: str
    transcription_id: Optional[str] = None
    result: Optional[dict] = None

class TranscriptionInfoResponse(BaseModel):
    success: bool
    transcription: Optional[dict] = None

# 创建服务实例
asr_service = ASRService()
video_service = VideoUploadService()

@router.post("/videos/{video_id}/transcribe", response_model=TranscriptionResponse)
async def transcribe_video(video_id: str, request: TranscriptionRequest = TranscriptionRequest()):
    """
    对视频进行语音识别和说话人识别
    
    - **video_id**: 视频ID
    - **language**: 语言代码 (可选，自动检测)
    """
    try:
        # 检查视频是否存在
        video_info = video_service.get_video_info(video_id)
        if not video_info['success']:
            raise HTTPException(status_code=404, detail="视频不存在")
        
        video_data = video_info['video_info']
        
        # 检查是否已提取音频
        if not video_data.get('audio_extracted'):
            raise HTTPException(status_code=400, detail="请先提取视频音频")

        # 获取音频路径（允许为空，由 ASR 服务内部处理）
        audio_path = video_data.get('audio_path')
        
        # 执行转录
        result = asr_service.transcribe_audio(
            video_id=video_id,
            audio_path=audio_path,
            language=request.language
        )
        
        return JSONResponse(content=result)
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(traceback.format_exc())  # ✅ 现在不会报 NameError
        return JSONResponse(
            status_code=500,
            content={"success": False, "message": f"转录失败: {str(e)}"}
        )

@router.get("/transcriptions/{transcription_id}", response_model=TranscriptionInfoResponse)
async def get_transcription(transcription_id: str):
    """
    获取转录结果
    
    - **transcription_id**: 转录ID
    """
    try:
        result = asr_service.get_transcription(transcription_id)
        return JSONResponse(content=result)
        
    except HTTPException as e:
        return JSONResponse(
            status_code=e.status_code,
            content={"success": False, "message": e.detail}
        )

@router.get("/videos/{video_id}/transcription", response_model=TranscriptionInfoResponse)
async def get_video_transcription(video_id: str):
    """
    获取视频的转录结果
    
    - **video_id**: 视频ID
    """
    try:
        result = asr_service.get_video_transcription(video_id)
        return JSONResponse(content=result)
        
    except HTTPException as e:
        return JSONResponse(
            status_code=e.status_code,
            content={"success": False, "message": e.detail}
        )

@router.get("/transcriptions", response_model=TranscriptionInfoResponse)
async def list_transcriptions(
    limit: int = Query(10, ge=1, le=100, description="每页数量"),
    offset: int = Query(0, ge=0, description="偏移量"),
    status: Optional[str] = Query(None, description="转录状态过滤")
):
    """
    获取转录列表
    
    - **limit**: 每页数量
    - **offset**: 偏移量
    - **status**: 转录状态过滤 (pending, processing, completed, failed)
    """
    try:
        from app.models.transcription import Transcription
        from app.utils.database import db_manager
        
        with db_manager.get_session() as session:
            query = session.query(Transcription)
            
            if status:
                query = query.filter(Transcription.status == status)
            
            transcriptions = query.order_by(Transcription.created_at.desc()).offset(offset).limit(limit).all()
            total = query.count()
            
            result = {
                'success': True,
                'transcriptions': [t.to_dict() for t in transcriptions],
                'total': total,
                'limit': limit,
                'offset': offset
            }
            
            return JSONResponse(content=result)
            
    except Exception as e:
        return JSONResponse(
            status_code=500,
            content={"success": False, "message": f"获取转录列表失败: {str(e)}"}
        ) 